package com.coder.baseapp.wrapper;

import org.reactivestreams.Subscription;

import java.util.Vector;

import javax.inject.Inject;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * @Author: Tua.CoderGui
 * *
 * @Date: 2017/3/11
 * *
 * Copyright (c) 2017 All Rights Reserved.
 */
public class RxManager {

    private RxBus mRxBus;

    /*管理Subscribers订阅*/
    private Vector<Subscription> mSubscriptions;

    /*管理Disposable订阅*/
    private CompositeDisposable mCompositeDisposable;

    @Inject
    public RxManager() {
        mRxBus = RxBus.getInstance();
        mSubscriptions = new Vector<Subscription>();
        mCompositeDisposable = new CompositeDisposable();
    }

    /**
     * RxBus订阅
     *
     * @param eventType
     * @param consumer
     * @param <T>
     */
    public <T> void onEvent(Class<T> eventType, Consumer<T> consumer) {
        //订阅Bus
        Flowable<T> flowable = mRxBus.toFlowable(eventType);

        //管理Disposable
        mCompositeDisposable.add(flowable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(consumer, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Logger.e(throwable.getMessage());
                    }
                }));

    }

    //发送rxbus
    public void post(Object content) {
        mRxBus.post(content);
    }

    /**
     * 单纯的Subscriber管理
     *
     * @param subscription
     */
    public void add(Subscription subscription) {
        mSubscriptions.add(subscription);
    }

    /**
     * 单纯的Disposable管理
     *
     * @param disposable
     */
    public void add(Disposable disposable) {
        mCompositeDisposable.add(disposable);
    }

    //exit
    public void exit() {
        mCompositeDisposable.dispose();
        mCompositeDisposable.clear();

        for (Subscription mSubscription : mSubscriptions) {
            mSubscription.cancel();
        }
        mSubscriptions.clear();
    }
}
